package com.example.disinfestation.controller;


import ch.qos.logback.core.joran.spi.XMLUtil;
import com.example.disinfestation.WXPay.HttpClientUtil;
import com.example.disinfestation.WXPay.WXPayConstants;
import com.example.disinfestation.WXPay.WXPayUtil;
import com.example.disinfestation.entity.Order;
import com.example.disinfestation.entity.Pest;
import com.example.disinfestation.entity.Pservices;
import com.example.disinfestation.mapper.OrderMapper;
import com.example.disinfestation.mapper.PestMapper;
import com.example.disinfestation.service.PservicesService;
import com.example.disinfestation.util.AESUtil;
import com.example.disinfestation.util.JsonResult;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description 微信支付
 * @Author DongPo
 */
@RequestMapping("wxPay")
@Controller
public class WXPayController extends BaseController{
//	@Autowired
//	private UserService userService;
//
//	@Autowired
//	private EvaluationPriceService evaluationPriceService;

	@Autowired
	OrderMapper orderMapper;
	@Autowired
	PestMapper pestMapper;
	@Autowired
	PservicesService pservicesService;


	//生成订单
	@RequestMapping("generateOrder")
	@ResponseBody
	public JsonResult<Void> generateOrder(String timess,String username,String phone,String region,String address,Integer pid,String openId){
		JsonResult result = new JsonResult();
		System.out.println("生成一个订单");
		try {
			// 拼接统一下单地址参数
//			Map<String, String> paraMap = new HashMap<>();

			// 生成随机订单号 当前时间+随机四位数
			String orderNum = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			int randomNum = (int)(new Random().nextDouble()*(9999-1000+1))+1000;
			orderNum = orderNum + randomNum;
			System.err.println(orderNum);

			Date createtime = new Date();//订单创建时间

//			Integer ordertype = 0;//订单状态，-1失败，0待支付，1支付成功

			Pservices pest = pservicesService.selectByPrimaryKey(pid);
			String header = pest.getHeader();
			String photo = pest.getPhoto();
			String artice = pest.getArticle();
			String money = pest.getMoney();

			String complete = "待付款";

			orderMapper.generateOrder(orderNum,header,photo,artice,money,timess,username,phone,region,address,createtime,pid,openId,complete);

			result.setState(SUCCESS);


		}catch (Exception e){
			result.setMessage("出现异常,订单生成失败");
		}
		return result;
	}




	//延伸服务生成订单
	@RequestMapping("GenerateOrderService")
	@ResponseBody
	public JsonResult<Void> GenerateOrderService(String price,String timess,String username,String phone,String region,String address,Integer pid,String openId){
		JsonResult result = new JsonResult();
		System.out.println("延伸服务生成一个订单");
		try {
			Double prices = Double.valueOf(price);
			System.out.println(prices);
			int pricess = (int) (prices*100);
			String money = String.valueOf(pricess);
			System.err.println("金额= "+money);

			// 生成随机订单号 当前时间+随机四位数
			String orderNum = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			int randomNum = (int)(new Random().nextDouble()*(9999-1000+1))+1000;
			orderNum = orderNum + randomNum;
			System.err.println(orderNum);

			Date createtime = new Date();//订单创建时间

//			Integer ordertype = 0;//订单状态，-1失败，0待支付，1支付成功

			Pservices pest = pservicesService.selectByPrimaryKey(pid);
			String header = pest.getHeader();
			String photo = pest.getPhoto();
			String artice = pest.getArticle();

			String complete = "待付款";

			orderMapper.generateOrder(orderNum,header,photo,artice,money,timess,username,phone,region,address,createtime,pid,openId,complete);

			result.setState(SUCCESS);


		}catch (Exception e){
			result.setMessage("出现异常,延伸服务订单生成失败");
		}
		return result;
	}



	//根据openID查询该用户的全部订单信息
	@RequestMapping("selectByOpenId")
	@ResponseBody
	public JsonResult<List<Order>> selectByOpenId(String openId){
		JsonResult result = new JsonResult();
		System.out.println("根据openID查询该用户的全部订单信息");
		try {
			List<Order> data = orderMapper.selectByOpenId(openId);
			result.setState(SUCCESS);
			result.setData(data);
		}catch (Exception e){
			result.setMessage("查询失败，出现异常");
		}
		return result;
	}


//	//根据订单id取消该订单，修改订单状态
//	@RequestMapping("updateById")
//	@ResponseBody
//	public JsonResult<List<Order>> updateById(Integer id){
//		JsonResult result = new JsonResult();
//		System.out.println("根据订单id取消该订单，修改订单状态");
//		try {
//			Integer ordertype = -1;
//			orderMapper.updateById(id,ordertype);
//			result.setState(SUCCESS);
//		}catch (Exception e){
//			result.setMessage("修改失败，出现异常");
//		}
//		return result;
//	}

	//根据订单id删除该订单
	@RequestMapping("deleteById")
	@ResponseBody
	public JsonResult<List<Order>> deleteById(Integer id){
		JsonResult result = new JsonResult();
		System.out.println("根据订单id取消该订单，修改订单状态");
		try {
			orderMapper.deleteById(id);
			result.setState(SUCCESS);
		}catch (Exception e){
			result.setMessage("修改失败，出现异常");
		}
		return result;
	}



	/*调用支付接口*/
	@RequestMapping("prePay")
	@ResponseBody
	public Map<String, Object> prePay(Integer id, HttpServletRequest request){

		// 返回参数
		Map<String, Object> resMap = new HashMap<>();


		//获取请求ip地址
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getRemoteAddr();
		}
		if(ip.indexOf(",")!=-1){
			String[] ips = ip.split(",");
			ip = ips[0].trim();
		}

		try {


			// 拼接统一下单地址参数
			Map<String, Object> paraMap = new HashMap<>();

			Order order =  orderMapper.selectByPrimaryKey(id);
			String body = order.getHeader();//商品名称
			String orderNum = order.getOrdernum();//订单号
			String openId = order.getOpenid();
			String money = order.getMoney();
			Integer price = Integer.valueOf(money);
//			Integer price = 1;//支付金额，单位：分，这边需要转成字符串类型，否则后面的签名会失败


			// 封装11个必需的参数
			paraMap.put("appid", WXPayConstants.APP_ID);
			paraMap.put("mch_id", WXPayConstants.MCH_ID);//商家ID
			paraMap.put("nonce_str", WXPayUtil.generateNonceStr());//获取随机字符串 Nonce Str
			paraMap.put("body", body);     //商品名称
			paraMap.put("out_trade_no", orderNum);//订单号
			paraMap.put("total_fee",price);    //测试改为固定金额
			paraMap.put("spbill_create_ip", ip);
			paraMap.put("notify_url",WXPayConstants.CALLBACK_URL);// 此路径是微信服务器调用支付结果通知路径
			paraMap.put("trade_type", "JSAPI");
			paraMap.put("openid", openId);


			String sign = WXPayUtil.generateSignature(paraMap, WXPayConstants.PATERNER_KEY);//商户密码
			//生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
			paraMap.put("sign", sign);

			//将所有参数(map)转xml格式
			String xml = WXPayUtil.mapToXml(paraMap);
			System.err.println("xml:"+xml);
			// 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder
			String unifiedorder_url = WXPayConstants.UNIFIEDORDER_URL;//统一下单接口
			System.out.println("统一下单接口unifiedorder_url:"+unifiedorder_url);
			//发送post请求"统一下单接口"返回预支付id:prepay_id
			String xmlStr = HttpClientUtil.sendPost(unifiedorder_url, xml);
			System.out.println("xmlStr:"+xmlStr);

			//以下内容是返回前端页面的json数据
			//预支付id
			String prepay_id = "";

			if (xmlStr.indexOf("SUCCESS") != -1) {
				Map<String, Object> map = WXPayUtil.xmlToMap(xmlStr);//XML格式字符串转换为Map
				prepay_id =  map.get("prepay_id").toString();
				System.err.println("prepay_id=  "+prepay_id);
			}
			Map<String, Object> payMap = new HashMap<String, Object>();
			// 封装所需6个参数调支付页面
			payMap.put("appId", WXPayConstants.APP_ID);
			payMap.put("timeStamp", WXPayUtil.getCurrentTimestamp()+"");//获取当前时间戳，单位秒
			payMap.put("nonceStr", WXPayUtil.generateNonceStr());//获取随机字符串 Nonce Str
			payMap.put("signType", "MD5");
			payMap.put("package", "prepay_id="+prepay_id);

			//生成带有 sign 的 XML 格式字符串
			String paySign = WXPayUtil.generateSignature(payMap, WXPayConstants.PATERNER_KEY);
			payMap.put("paySign", paySign);

			// 封装正常情况返回数据
			resMap.put("success",true);
			resMap.put("payMap",payMap);
		} catch (Exception e) {
			// 封装异常情况返回数据
			resMap.put("success",false);
			resMap.put("message","调用统一订单接口错误");
			e.printStackTrace();
		}
		return resMap;
	}

	/*支付成功回调*/
	@RequestMapping("callBack")
	public JsonResult callBack(HttpServletRequest request, HttpServletResponse response){
		JsonResult result = new JsonResult();
		System.err.println("微信支付成功,微信发送的callback信息,请注意修改订单信息");
		InputStream is = null;
		String resXml = "";
		try {
			is = request.getInputStream();//获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
			String xml = WXPayUtil.inputStream2String(is);
			Map<String, Object> notifyMap = WXPayUtil.xmlToMap(xml);//将微信发的xml转map

			if(notifyMap.get("return_code").equals("SUCCESS")){


				String ordersNum = notifyMap.get("out_trade_no").toString();//商户订单号
				//处理订单状态
//				String openid = notifyMap.get("openid");
				Date zhifutime = new Date();
				Integer ordertype = 1;//1支付完成
				String complete = "待服务";
				try {
					orderMapper.updateByOrdersNum(ordersNum,ordertype,zhifutime,complete);
					result.setData(SUCCESS);
					result.setData("支付回调成功，修改订单状态为支付成功");
					//告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可

//					response.getWriter().write(XMLUtil.setXML("SUCCESS", "OK")); // 告诉微信服务器，我收到信息了，不要在调用回调action了
//					StringBuffer s = new StringBuffer();
//					s.append("<xml>");
//					s.append("<return_code><![CDATA[SUCCESS]]></return_code>");
//					s.append("<return_msg><![CDATA[OK]]></return_msg>");
//					s.append("</xml>");
//					response.getWriter().write(String.valueOf(s));
					resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
							+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
					BufferedOutputStream out = new BufferedOutputStream(
							response.getOutputStream());
					out.write(resXml.getBytes());
					out.flush();
					out.close();

					System.err.println("返回给微信的值："+resXml.getBytes());
					is.close();
				}catch (Exception e){
					result.setMessage("订单状态修改失败");
				}


			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}





	/*调用退款接口，取消订单*/
	@RequestMapping("refund")
	@ResponseBody
	public Map<String, Object> refund(Integer id,HttpServletResponse response){

		// 返回参数
		Map<String, Object> resMap = new HashMap<>();
		Date newtime = new Date();



		String resXml = "";
		try {


			// 拼接统一下单地址参数
			Map<String, Object> paraMap = new HashMap<>();

			Order order =  orderMapper.selectByPrimaryKey(id);

			String orderNum = order.getOrdernum();//订单号
			String money = order.getMoney();//金额
//			Integer price = 1;//支付金额，单位：分，这边需要转成字符串类型，否则后面的签名会失败
			Integer price = Integer.valueOf(money);


			// 封装必需的参数
			paraMap.put("appid", WXPayConstants.APP_ID);
			paraMap.put("mch_id", WXPayConstants.MCH_ID);//商家ID
			paraMap.put("nonce_str", WXPayUtil.generateNonceStr());//获取随机字符串 Nonce Str
			paraMap.put("out_trade_no", orderNum);//订单号
			paraMap.put("out_refund_no", orderNum);//商户退款单号
			paraMap.put("total_fee",price);    //测试改为固定金额  订单金额
			paraMap.put("refund_fee",price);    //退款金额
//			paraMap.put("notify_url", WXPayConstants.notify_url);   //退款路径

			String sign = WXPayUtil.generateSignature(paraMap, WXPayConstants.PATERNER_KEY);//商户密码
			//生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
			paraMap.put("sign", sign);

			//将所有参数(map)转xml格式
			String xml = WXPayUtil.mapToXml(paraMap);
			System.out.println("xml:"+xml);
			// 退款 https://api.mch.weixin.qq.com/secapi/pay/refund
			String refund_url = WXPayConstants.REFUND_URL;//申请退款路径接口
			System.out.println("refund_url:"+refund_url);
			//发送post请求"申请退款"
			String xmlStr = HttpClientUtil.doRefund(refund_url, xml);
			System.out.println("退款xmlStr:"+xmlStr);
			/*退款成功回调修改订单状态*/
			if (xmlStr.indexOf("SUCCESS") != -1) {
				Map<String, Object> map = WXPayUtil.xmlToMap(xmlStr);//XML格式字符串转换为Map
				if(map.get("return_code").equals("SUCCESS")){
					resMap.put("success",true);//此步说明退款成功
					resMap.put("data","退款成功");
					System.out.println("退款成功");
					Date refundtime = new Date();
					Integer ordertype = -1;//-1取消订单
					String complete = "已取消";
					try {
					orderMapper.updateRefundByOrdersNum(orderNum,ordertype,refundtime,complete);

						//告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
						resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
								+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
						BufferedOutputStream out = new BufferedOutputStream(
								response.getOutputStream());
						out.write(resXml.getBytes());
						out.flush();
						out.close();

						System.err.println("返回给微信的值："+resXml.getBytes());
					}catch (Exception e){
						resMap.put("fail","订单状态修改失败");
					}


				}


			}else {
				resMap.put("success","fail");//此步说明退款成功
				resMap.put("data","退款失败");
			}



		} catch (Exception e) {
			e.printStackTrace();
		}
		return resMap;
	}



//	/*退款成功回调*/
//	@RequestMapping("notifyUrl")
//	public JsonResult notifyUrl(HttpServletRequest request, HttpServletResponse response){
//		JsonResult result = new JsonResult();
//		System.err.println("微信订单退款成功,微信发送的notifyUrl信息,请注意修改订单信息");
//		InputStream is = null;
//		String resXml = "";
//		try {
//			is = request.getInputStream();//获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
//			String xml = WXPayUtil.inputStream2String(is);
//			Map<String, Object> notifyMap = WXPayUtil.xmlToMap(xml);//将微信发的xml转map
//			System.out.println("notifyMap集合= "+notifyMap);
//
//			if(notifyMap.get("return_code").equals("SUCCESS")){
//				System.out.println("退款111111111111111111");
//
////				String req_info = notifyMap.get("req_info").toString();//得到信息进行解密
////				AESUtil.decryptData(req_info);
//
//
//				//处理订单状态
//				System.out.println("退款22222222222222222222");
//				Date refundtime = new Date();
//				Integer ordertype = -1;//-1取消订单
//				String complete = "已取消";
//				try {
////					orderMapper.updateRefundByOrdersNum(ordersNum,ordertype,refundtime,complete);
//					result.setData(SUCCESS);
//					result.setData("支付退款成功，修改订单状态为取消成功");
//					//告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
//
//
//					resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
//							+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
//					BufferedOutputStream out = new BufferedOutputStream(
//							response.getOutputStream());
//					out.write(resXml.getBytes());
//					out.flush();
//					out.close();
//
//					System.err.println("返回给微信的值："+resXml.getBytes());
//
//					is.close();
//				}catch (Exception e){
//					result.setMessage("订单状态修改失败");
//				}
//
//
//			}
//
//		} catch (Exception e) {
//			e.printStackTrace();
////			result.setMessage("退款回调失败");
//		}
//		return result;
//	}






}
